<template>
  <view class="uploading-box" :style="{ height: viewHeight }">
    <view class="honor-up">
      <uni-list>
        <uni-list-item
          thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
          thumb-size="min"
          title="组织类型"
          @click="setPopupData('organizationType')"
          link
          :rightText="listItemRightText.organizationType"
        />
        <uni-list-item
          thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
          thumb-size="min"
          v-if="
            educationData.education == '' &&
            listItemRightText.organizationType == '个人'
          "
          title="学历"
          @click="setPopupData('education')"
          link
          :rightText="listItemRightText.education"
        />
        <uni-list-item
          thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
          thumb-size="min"
          title="职称"
          v-if="
            educationData.jobTitle == '' &&
            listItemRightText.organizationType == '个人'
          "
          @click="setPopupData('technical')"
          link
          :rightText="listItemRightText.technical"
        />
        <uni-list-item
          thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
          thumb-size="min"
          title="是否公开"
          @click="setPopupData('isOpen')"
          :rightText="listItemRightText.isOpen"
          link
        />
        <uni-list-item
          title="荣誉名称"
          thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
          thumb-size="min"
        >
          <template v-slot:footer>
            <input
              style="width: 500rpx; text-align: right; font-size: 30rpx"
              class="uni-input"
              placeholder="请输入证书或奖项等荣誉名称"
              v-model="honorName"
            />
          </template>
        </uni-list-item>
        <uni-list-item
          thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
          thumb-size="min"
          title="荣誉等级"
          @click="setPopupData('honourLevel')"
          :rightText="listItemRightText.honourLevel"
          link
        />
        <uni-list-item title="荣誉描述" />
        <uni-easyinput
          style-other="  margin: 0 30rpx;font-size: 30rpx;"
          :inputBorder="false"
          type="textarea"
          placeholderStyle="font-size: 30rpx;"
          v-model="honorDescribe"
          placeholder="请输入内容"
        />
        <uni-list-item
          thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
          thumb-size="min"
          title="上传图片 "
        />
        <uni-file-picker
          ref="imgPickerRef"
          style-other="padding-right: 30rpx; margin-left: 30rpx;margin-bottom: 30rpx;width: 96vw;"
          file-mediatype="image"
          limit="9"
          title=""
          @select="uploadFile"
          @delete="handleDeleteUploadFile"
          @fail="uploadFail"
        />
        <text style="padding-left: 20rpx; margin-bottom: 20rpx">
          图片文件大小限制在1MB以内
        </text>
      </uni-list>
    </view>

    <view class="comment-box">
      <view class="go-comment" @click="handleSubmitAudit">提交审核</view>
    </view>
    <uni-popup
      ref="popup"
      type="bottom"
      round
      background-color="#ffffff"
      @mask-click="popupHandleClose"
    >
      <template v-for="(item, index) in checkRadioPopupList" :key="index">
        <view class="popup-uploading-box" v-if="item.show">
          <view class="title-radio">{{ item.radioTitle }}</view>
          <checkRadio
            :list="item.radioList"
            @getCheckData="(value) => setCheckedData(value, item.type)"
            :checkedName="item.currentCheckedValue"
          />
        </view>
      </template>
    </uni-popup>

    <uni-popup
      ref="goRealNameAuthenticationPopupRef"
      type="center"
      round
      background-color="#fff"
      @mask-click="handleCloseGoRealNamePopup"
    >
      <view class="go-real-name-authentication-popup">
        <view class="go-real-name-authentication-popup-text">
          您还未实名认证
        </view>
        <view
          class="go-real-name-authentication-popup-btn"
          @click="goRealNamePage"
        >
          去实名认证
        </view>
      </view>
    </uni-popup>

    <!-- 登录弹窗 -->
    <loginDialog
      @on-off="getHome"
      @on-make="headelMake"
      :indicate="userLoginDialog"
    >
    </loginDialog>
  </view>
</template>

<script setup>
import loginDialog from "@/components/login/index.vue";
import { ref, toRaw, watch, onMounted, nextTick } from "vue";
import uniDataChecklist from "@/uni_modules/uni-data-checkbox/components/uni-data-checkbox/uni-data-checkbox.vue";
import { upHonorData } from "@/api/upLoading/index.js";
import { getUserPositionAndEducationAPi } from "@/api/upLoading/release.js";
import { getConfigEnterpriseFieldsApi } from "@/api/honour/search";
import checkRadio from "./componts/checkRadio.vue";
import { getTitleViewHeight } from "@/utils/utils";
import UniFilePicker from "@/uni_modules/uni-file-picker/components/uni-file-picker/uni-file-picker.vue";
import { getUserInfoApi } from "@/api/user";
import UniListItem from "@/uni_modules/uni-list/components/uni-list-item/uni-list-item.vue";
import UniList from "@/uni_modules/uni-list/components/uni-list/uni-list.vue";
import UniEasyinput from "@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue";
import UniPopup from "@/uni_modules/uni-popup/components/uni-popup/uni-popup";
import { customNav } from "@/utils/customNav";
import { onShow, onTabItemTap } from "@dcloudio/uni-app";

const userLoginDialog = ref(false);
const userLoginInfo = ref("");
/** 用户信息部分start */
//用户信息
const userInfo = ref({});
const educationData = ref({
  education: "",
  jobTitle: "",
});
/**
 * 获取用户信息
 * @returns {Promise<void>}
 */
const getUserInfo = async () => {
  const res = await getUserInfoApi();
  const { code, data } = res;
  if (code === 200) {
    userInfo.value = data;
  }
};

function getHome() {
  uni.switchTab({
    url: "/pages/index/index",
  });
}
const getUserPositionAndEducation = async () => {
  const user = await getUserPositionAndEducationAPi();
  const { code, data } = user;
  if (code === 200) {
    console.log("getUserPositionAndEducation获取成功", data);
    if (data) {
      educationData.value = data;
    }
  } else {
    console.log("getUserPositionAndEducation", data);
  }
};
/** 用户信息部分end */

/* checkRadio弹出层相关start */
const listItemRightText = ref({
  organizationType: "请选择组织类型",
  isOpen: "请选择是否公开",
  education: "请选择学历",
  technical: "请选择职称",
  honourLevel: "请选择荣誉等级",
});
const checkRadioPopupList = ref([
  {
    show: false,
    type: "organizationType",
    radioTitle: "组织类型",
    radioList: [
      {
        text: "企业",
        value: 0,
        show: true,
      },
      {
        text: "个人",
        value: 1,
        show: true,
      },
    ],
    currentCheckedValue: "",
  },
  {
    show: false,
    type: "isOpen",
    radioTitle: "是否公开",
    radioList: [
      {
        text: "否",
        value: 0,
      },
      {
        text: "是",
        value: 1,
      },
    ],
    currentCheckedValue: "",
  },
  {
    show: false,
    type: "education",
    radioTitle: "学历",
    radioList: [],
    currentCheckedValue: "",
  },
  {
    show: false,
    type: "technical",
    radioTitle: "职称",
    radioList: [],
    currentCheckedValue: "",
  },
  {
    show: false,
    type: "honourLevel",
    radioTitle: "荣誉等级",
    radioList: [
      {
        text: "国际级",
        value: "国际级",
      },
      {
        text: "国家级",
        value: "国家级",
      },
      {
        text: "省部级",
        value: "省部级",
      },
      {
        text: "市级",
        value: "市级",
      },
      {
        text: "区县级",
        value: "区县级",
      },
    ],
  },
]);
const popup = ref();
const goRealNameAuthenticationPopupRef = ref();

/**
 * 设置checkRadio弹窗数据
 */
const setPopupData = (type) => {
  // const { enterpriseManger } = userInfo.value || {};
  // if (enterpriseManger === 0) {
  //   //不是管理员就只显示个人
  //   const findPopupData = checkRadioPopupList.value.find(
  //     (popup) => popup.type === "organizationType"
  //   );
  //   const { radioList } = findPopupData || {};
  //   const enterpriseRadioIndex = radioList.findIndex(
  //     (radio) => radio.text === "企业"
  //   );
  //   enterpriseRadioIndex !== -1 && radioList.splice(enterpriseRadioIndex, 1);
  // }
  checkRadioPopupList.value.find((popup) => popup.type === type).show = true;
  popup.value.open();
};

/**
 * 监听点击mask关闭popup事件
 */
const popupHandleClose = () => {
  checkRadioPopupList.value.forEach((popup) => (popup.show = false));
};

/**
 * 监听实名认证弹窗手动关闭事件
 */
const handleCloseGoRealNamePopup = () => {
  checkRadioPopupList.value.find(
    (popup) => popup.type === "organizationType"
  ).currentCheckedValue = "";
  listItemRightText.value.organizationType = "请选择组织类型";
};

/**
 * 跳转到实名认证页面
 */
const goRealNamePage = () => {
  customNav("/package_user/pages/user/name-authentication");
};

/**
 * 设置radio选择数据
 * @param data
 * @param type
 */
const setCheckedData = (data, type) => {
  console.log(data);
  console.log(type);

  const findDataByType = checkRadioPopupList.value.find(
    (popup) => popup.type === type
  );
  findDataByType.currentCheckedValue = data;
  const findRadioData = findDataByType.radioList.find(
    (radio) => radio.value === data
  );
  if (type === "organizationType" && findRadioData.text === "个人") {
    const { hasIdCard } = userInfo.value;
    console.log("userInfo.value", userInfo.value);
    console.log("hasIdCard", hasIdCard);
    if (!hasIdCard) {
      goRealNameAuthenticationPopupRef.value.open();
    }
  }
  listItemRightText.value[type] = findRadioData.text;
  checkRadioPopupList.value.forEach((popup) => (popup.show = false));
  popup.value.close();
};
/* checkRadio弹出层相关start */

/*  图片上传相关 */
// 图片地址
const imgPickerRef = ref();
const imgFile = ref("");
/**
 * 上传图片文件
 * @param res
 * @returns {Promise<void>}
 */
const uploadFile = async (res) => {
  const { tempFilePaths, tempFiles } = res || {};
  console.log(res);
  const maxSize = 1 * 1024 * 1024;
  const tempFile = tempFilePaths[0];
  if (maxSize >= tempFiles[0].size) {
    uni.uploadFile({
      url: "/ht-user/user/upload",
      filePath: tempFile,
      name: "file",
      formData: {
        type: 2,
      },
      success: (res) => {
        console.log("上传大小", res);
        const { statusCode, data } = res;
        if (statusCode === 200) {
          const parseData = JSON.parse(data);
          if (imgFile.value === "") {
            imgFile.value = parseData.data;
          } else {
            imgFile.value += `ht:url${parseData.data}`;
          }
        }
      },
    });
  } else {
    handleDeleteUploadFile({
      tempFilePath: tempFilePaths[0],
      tempFile: tempFiles[0],
    });
    uni.showToast({
      title: "图片大小超过1MB",
      icon: "error",
    });
  }
};

/**
 * 监听手动删除图片
 * @param res
 */
const handleDeleteUploadFile = (res) => {
  console.log("删除", res);
  console.log("删除", imgFile.value);
  const imgFileSlice = imgFile.value.split("ht:url");
  const findDelItemIndex = imgFileSlice.findLastIndex((item) =>
    item.includes(res.tempFile.name)
  );
  findDelItemIndex !== -1 && imgFileSlice.splice(findDelItemIndex, 1);
  imgFile.value = imgFileSlice.join("ht:url");
};

const uploadFail = (res) => {
  console.log(res);
};
const honorName = ref("");
const honorDescribe = ref("");

const handleSubmitAudit = async () => {
  if (!userLoginInfo.value) {
    return uni.showToast({
      title: "请先登录",
      icon: "error",
    });
  }

  console.log("checkRadioPopupList.value", checkRadioPopupList.value);

  const isOpenValue = checkRadioPopupList.value.find(
    (popup) => popup.type === "isOpen"
  )?.currentCheckedValue;
  console.log("isOpenValue", isOpenValue);
  const typeValue = checkRadioPopupList.value.find(
    (popup) => popup.type === "organizationType"
  )?.currentCheckedValue;
  console.log("typeValue", typeValue);
  const honourLevelValue = checkRadioPopupList.value.find(
    (popup) => popup.type === "honourLevel"
  )?.currentCheckedValue;
  const education = checkRadioPopupList.value.find(
    (popup) => popup.type === "education"
  )?.currentCheckedValue;
  const jobTitle = checkRadioPopupList.value.find(
    (popup) => popup.type === "technical"
  )?.currentCheckedValue;
  console.log("jobTitle", jobTitle);
  function judge() {
    if (educationData.value.education == "") {
      if (education.length == 0 || jobTitle.length == 0) {
        return true;
      } else {
        return false;
      }
    } else {
      return false;
    }
  }
  function honourLevelJudge() {
    if (honourLevelValue == undefined) {
      return true;
    } else if (honourLevelValue.length == 0) {
      return true;
    } else {
      return false;
    }
  }
  if (typeValue === "企业") {
    if (
      isOpenValue === "" ||
      typeValue === "" ||
      honorName.value.length == 0 ||
      honourLevelJudge() ||
      imgFile.value == ""
    ) {
      return uni.showToast({
        title: "请填写完相关资料",
        icon: "error",
      });
    }
  } else {
    if (
      isOpenValue === "" ||
      typeValue === "" ||
      honorName.value.length == 0 ||
      honourLevelJudge() ||
      imgFile.value == "" ||
      judge()
    ) {
      return uni.showToast({
        title: "请填写完相关资料",
        icon: "error",
      });
    }
  }

  const params = {
    isOpen: isOpenValue,
    resourceUrl: imgFile.value,
    type: typeValue === 1 ? 2 : typeValue,
    honorName: honorName.value,
    honorDetail: honorDescribe.value,
    education:
      educationData.value.education !== ""
        ? educationData.value.education
        : education,
    jobTitle:
      educationData.value.jobTitle !== ""
        ? educationData.value.jobTitle
        : jobTitle,
    honorGrade: honourLevelValue,
  };
  const res = await upHonorData(params);
  const { code, data } = res;
  if (code === 200) {
    resetForm();
    await customNav("success");
  }
};

/**
 * 重置表单
 */
const resetForm = () => {
  checkRadioPopupList.value = checkRadioPopupList.value.map((o) => {
    return {
      show: false,
      type: o.type,
      radioTitle: o.radioTitle,
      radioList: o.radioList,
      currentCheckedValue: "",
    };
  });
  listItemRightText.value = {
    organizationType: "请选择组织类型",
    isOpen: "请选择是否公开",
    education: "请选择学历",
    technical: "请选择职称",
    honourLevel: "请选择荣誉等级",
  };
  honorName.value = "";
  honorDescribe.value = "";
  imgPickerRef.value.clearFiles({});
};

const viewHeight = ref("");
async function getConfigEnterpriseFields() {
  const params = {
    type: 2,
  };
  let res = await getConfigEnterpriseFieldsApi(params);
  console.log(res);
  const { code, data } = res;
  if (code == 200) {
    console.log(data);
    checkRadioPopupList.value = checkRadioPopupList.value.map((o) => {
      if (o.radioTitle == "学历" || o.radioTitle == "职称") {
        let listData = {};
        if (o.radioTitle == "学历") {
          listData = data.filter((o) => o.filedName == "学历分类")[0];
        } else {
          listData = data.filter((o) => o.filedName == "职称层级")[0];
        }

        console.log("listData", listData);
        return {
          show: o.show,
          type: o.type,
          radioTitle: o.radioTitle,
          radioList: listData.children.map((v) => {
            return {
              text: v.filedName,
              value: v.filedName,
            };
          }),
          currentCheckedValue: o.currentCheckedValue,
        };
      } else {
        return o;
      }
    });
    console.log(checkRadioPopupList.value);
  }
  const typeData = {
    type: 7,
  };
  const typeList = await getConfigEnterpriseFieldsApi(typeData);
  if (typeList.code == 200) {
    checkRadioPopupList.value = checkRadioPopupList.value.map((o) => {
      if (o.radioTitle == "荣誉等级") {
        let listData = {};
        if (o.radioTitle == "荣誉等级") {
          listData = typeList.data.filter((o) => o.filedName == "荣誉等级")[0];
        }
        console.log("listData", listData);
        return {
          show: o.show,
          type: o.type,
          radioTitle: o.radioTitle,
          radioList: listData.children.map((v) => {
            return {
              text: v.filedName,
              value: v.filedName,
            };
          }),
          currentCheckedValue: o.currentCheckedValue,
        };
      } else {
        return o;
      }
    });
  }
}
/**
 * 登录弹窗关闭事件
 */
const headelMake = () => {
  userLoginDialog.value = false;
  userLoginInfo.value = uni.getStorageSync("token");
  getUserInfo();
  getUserPositionAndEducation();
};
onMounted(() => {
  nextTick(() => {
    // 先隐藏
    // viewHeight.value = `calc(100vh - ${getTitleViewHeight() + 125}rpx)`
  });
});
onTabItemTap(async (item) => {
  const { text } = item;
  if (text === "荣誉上传") {
    userLoginInfo.value = uni.getStorageSync("token");
    /*if (!userLoginInfo.value) {
      userLoginDialog.value = true;
    } else {*/
      getUserInfo();
      getUserPositionAndEducation();
    // }
  }
});
onShow(() => {
  getConfigEnterpriseFields();
  if (goRealNameAuthenticationPopupRef.value) {
    goRealNameAuthenticationPopupRef.value.close();
  }
});
</script>

<style scoped lang="less">
.uploading-box {
  width: 100vw;
  overflow-x: hidden;
  overflow-y: auto;
  padding-bottom: 150rpx;
  .upLoadbtn {
    width: 200rpx;
    height: 200rpx;
    display: flex;
    align-items: center;
  }

  .uni-data-checklist-uploading {
    padding: 0 150rpx;
    background-color: #f7f8fd;
    width: 60vw;
    position: sticky;
    top: 0rpx;
    z-index: 10;
    // margin: 0 auto;
  }

  .honor-up {
    .van-cell-group {
      .van-cell {
        font-size: 31rpx;
        color: #272636;
        font-family: "ali";

        .van-cell__value {
          color: #272636;
        }

        .up-load-box {
          height: 200rpx;
          width: 200rpx;
          background-color: #f7f8fd;
          text-align: center;
          line-height: 200rpx;
        }
      }
    }
  }

  .application-evaluation {
    .application-evaluation-text {
      font-family: "ali";
      color: #9b9b9b;
      font-size: 24rpx;
      padding: 0 30rpx;
    }

    .van-cell-group {
      margin: 20rpx 0;

      .van-cell {
        font-size: 31rpx;
        color: #272636;
        font-family: "ali";

        .van-cell__value {
          color: #272636;
        }
      }
    }
  }

  .comment-box {
    width: 100vw;
    height: 120rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    .go-comment {
      background-image: linear-gradient(to right, #ff934c, #fc686f);
      width: 90vw;
      height: 70rpx;
      border-radius: 50rpx;
      text-align: center;
      line-height: 70rpx;
      color: #ffffff;
      font-size: "ali-m";
      font-size: 32rpx;
    }
  }

  .popup-uploading-box {
    // min-height: 400rpx;

    .title-radio {
      width: 100vw;
      text-align: center;
      margin: 30rpx 0;
      font-family: "ali-m";
    }
  }

  :deep(.uni-easyinput__content) {
    padding-right: 30rpx;
  }

  .go-real-name-authentication-popup {
    display: flex;
    flex-direction: column;
    justify-content: space-around;
    width: 40vw;
    height: 300rpx;
    border-radius: 40rpx;
    padding: 20rpx 40rpx;
    font-family: "ali";

    &-text {
      height: 100rpx;
      line-height: 100rpx;
      text-align: center;
      font-weight: 600;
    }

    &-btn {
      width: 100%;
      height: 60rpx;
      line-height: 60rpx;
      color: #fff;
      font-weight: 700;
      text-align: center;
      background-color: #00a4ff;
      border-radius: 40rpx;
    }
  }

  :deep(.uni-popup__wrapper) {
    border-radius: 30rpx;
  }
}
</style>
